﻿using CL.Game.BLL;
using CL.Game.BLL.Tools;
using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace CL.Mobile
{
    public partial class wxregister : System.Web.UI.Page
    {
        Log log = new Log("wxregister");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
            }
        }

        protected void BindData()
        {
            //检测是否为微信登陆
            if (Request.UserAgent.ToLower().Contains("micromessenger"))
            {
                var wechat = new WeChatHelper(this);
                wechat.redirecturl = HttpUtility.UrlEncode(this.Request.Url.ToString().Replace("wxregister.aspx", "app.html"));
                log.Write(string.Format("redirecturl:{0}", wechat.redirecturl));
                var userInfo = wechat.GetOAuthSnsApiUserInfo();
                if (userInfo != null)
                {
                    try
                    {
                        string uid = Request["uid"];
                        log.Write(string.Format("uidencrypt:{0}", uid));
                        long uuid = 0;
                        if (!string.IsNullOrEmpty(uid))
                            long.TryParse(this.Decrypt(uid), out uuid);
                        log.Write(string.Format("uuid:{0}", uuid));

                        string sign = Request["sign"];
                        new Log("wxregister").Write(string.Format("sign:{0}", sign));
                        int source = 0; //0.pc，1.android，2.ios，3.ipad
                        int.TryParse(Request["Source"], out source);
                        var rec = new UsersBLL().ActivtiyRegister_WX(uuid, userInfo.unionid, (short)source, userInfo.nickname, userInfo.headimgurl);
                        log.Write(Newtonsoft.Json.JsonConvert.SerializeObject(rec));
                    }
                    catch (Exception ex)
                    {
                        log.Write(string.Format("参数读取失败:{0}", ex));
                    }
                }
            }
        }
        #region MD5加密
        public string MD5Str(string pwd, bool IsUTF8 = false)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] data = !IsUTF8 ? Encoding.Default.GetBytes(pwd) : Encoding.UTF8.GetBytes(pwd);
            byte[] md5data = md5.ComputeHash(data);
            md5.Clear();
            string str = "";
            for (int i = 0; i < md5data.Length; i++)
            {
                str += md5data[i].ToString("x").PadLeft(2, '0');

            }
            return str;
        }
        #endregion
        #region ========解密========
        private string cryptKey = GetMd5Hash("Caile");
        private string cryptIV = GetMd5Hash("Game");
        public static string GetMd5Hash(string input)
        {
            MD5 md5Hash = MD5.Create();
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            return sBuilder.ToString().Substring(0, 8);
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public string Decrypt(string Text)
        {
            return Decrypt(Text, cryptKey, cryptIV);
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public string Decrypt(string Text, string sKey)
        {
            return Decrypt(Text, GetMd5Hash(sKey), cryptIV);
        }

        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public string Decrypt(string Text, string sKey, string sIv)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;
            len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sIv);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }

        #endregion
        #region Http请求
        public string HttpPost(string url, string param, IDictionary<object, string> headers = null, bool IsUFT8 = false,
            string UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36")
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = !IsUFT8 ? "application/x-www-form-urlencoded" : "text/xml;charset=utf-8";
            request.Accept = "*/*";
            request.Timeout = 5000;
            request.AllowAutoRedirect = false;
            request.UserAgent = UserAgent;

            if (headers != null)
            {
                foreach (var v in headers)
                {
                    if (v.Key is HttpRequestHeader)
                        request.Headers[(HttpRequestHeader)v.Key] = v.Value;
                    else
                        request.Headers[v.Key.ToString()] = v.Value;
                }
            }

            StreamWriter requestStream = null;
            WebResponse response = null;
            string responseStr = null;

            try
            {
                requestStream = new StreamWriter(request.GetRequestStream());
                requestStream.Write(param);
                requestStream.Close();

                response = request.GetResponse();
                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                requestStream = null;
                response = null;
            }

            return responseStr;
        }
        #endregion
    }
}